package app;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/*
 * Parses the data from reader to an ArrayList for writer
 */
public class Parser {
	
	Parser(Reader reader) throws IOException {
		this.parseFromList(reader);
	}
	
	private String cpData;
	private ArrayList<String> unformattedList;

	public ArrayList<String> getUnformattedList() {
		return unformattedList;
	}

	private void parseFromList(Reader reader) throws IOException {
		cpData = reader.getRawData();
		String[] pieces = cpData.split(":");
		unformattedList = formatString(pieces);
	}
	
	/*
	 * catch irregularities: {" and }}
	 */
	private ArrayList<String> formatString(String[] pieces) {
		ArrayList<String> dataList = new ArrayList<String>();
		String[] parts = new String[2];
		String temp;
		
		dataList.add(StrVar.DAILY.getVarName());
		for(int i = 1; i < pieces.length; i++) {

			if (pieces[i].startsWith("{\"")) {
				temp = pieces[i].substring(2, pieces[i].length()-1);
				temp = epochConvert(temp);
				dataList.add(temp);
			}
			else if (pieces[i].endsWith("}}")) {
				temp = pieces[i].substring(0, pieces[i].length()-2);
				dataList.add(temp);
			}
			else {
				parts = pieces[i].split(",");
				temp = parts[0];
				if (temp.contains("}")) {
					temp = temp.substring(0, temp.length()-1);
					temp = epochConvert(temp);
				}
				dataList.add(temp);
				temp = parts[1].substring(1, parts[1].length()-1);
				temp = epochConvert(temp);
				dataList.add(temp);
			}
		}
		
		return dataList;
	}
	
	/*
	 * Converts the weirdly used epoch time that Jagex uses to 
	 * a date format that humans can actually interpret.
	 */
	private String epochConvert(String s) {
		if (s.length() == 13) {
			Long epoch = Long.parseLong(s);
			epoch = epoch + 28800000;
			Date date = new Date(epoch);
			SimpleDateFormat sdf = new SimpleDateFormat(StrVar.DATEFMT.getVarName());
			String dateTime = sdf.format(date);
			return dateTime;
		}
		else {
			return s;
		}
		
	}
}
